package com.mall.seckill.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.common.constants.ScekillConstants;
import com.common.utils.R;
import com.mall.seckill.dto.SeckillSkuRedisDto;
import com.mall.seckill.feign.CouponFeignService;
import com.mall.seckill.feign.ProductFeignService;
import com.mall.seckill.service.SeckillService;
import com.mall.seckill.vo.SeckillRelationEntity;
import com.mall.seckill.vo.SeckillSessionEntity;
import com.mall.seckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public void uploadSeckillSku3Days() {
        R r = couponFeignService.getLates3DaysSession();
        if (r.getCode() == 0){
            String json = (String) r.get("data");
            List<SeckillSessionEntity> data = JSON.parseArray(json, SeckillSessionEntity.class);
            saveSessionInfos(data);
            saveSessionSkuInfos(data);
        }
    }

    /**
     * 每日活动对应的sku信息
     * @param data
     */
    private void saveSessionSkuInfos(List<SeckillSessionEntity> data) {
        data.forEach(session ->{
            BoundHashOperations<String, Object, Object> boundHashOps = stringRedisTemplate.boundHashOps(ScekillConstants.SKU_CACHE_PREFIX);
            SeckillSkuRedisDto dto = new SeckillSkuRedisDto();
            session.getRelationEntities().forEach(item ->{
                Boolean flag = stringRedisTemplate.hasKey(item.getSkuId().toString());
                if (Boolean.TRUE.equals(flag)){
                    return;
                }
                R r = productFeignService.info(item.getSkuId());
                if (r.getCode() == 0){
                    SkuInfoVo skuInfoVo = (SkuInfoVo) r.get("skuInfo");
                    dto.setSkuInfoVo(skuInfoVo);
                }
//                dto.setSkuId(item.getSkuId());
//                dto.setSeckillPrice(item.getSeckillPrice());
//                dto.setSeckillCount(item.getSeckillCount());
//                dto.setSeckillLimit(item.getSeckillLimit());
//                dto.setSeckillSort(item.getSeckillSort());
                BeanUtils.copyProperties(item,dto);
                dto.setStartTime(session.getStartTime().getTime());
                dto.setEndTime(session.getEndTime().getTime());
                String code = UUID.randomUUID().toString().replace("-","");
                dto.setRandCode(code);
                RSemaphore semaphore = redissonClient.getSemaphore(ScekillConstants.SKU_STOCK_SEMAPHORE + code);
                semaphore.trySetPermits(item.getSeckillCount().intValue());
                    boundHashOps.put(item.getSkuId().toString(), dto);
        });
        });
    }

    /**
     * 保存每日活动
     * @param data
     */
    private void saveSessionInfos(List<SeckillSessionEntity> data) {
        for (SeckillSessionEntity datum : data) {
            Date startTime = datum.getStartTime();
            Date endTime = datum.getEndTime();
            String key = ScekillConstants.SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean flag = stringRedisTemplate.hasKey(key);
            if (!flag) {
                List<String> list = datum.getRelationEntities().stream().map(item -> {
                    return item.getPromotionSessionId() + "_" + item.getSkuId().toString();
                }).collect(Collectors.toList());
                stringRedisTemplate.opsForList().leftPushAll(key, list);
            }
        }
    }
    /**
     * 查询出商品
     */
    @Override
    public List<SeckillSkuRedisDto> getCurrentSkus() {
        long time = new Date().getTime();
        Set<String> keys = stringRedisTemplate.keys(ScekillConstants.SESSION_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(ScekillConstants.SESSION_CACHE_PREFIX, "");
            String[] split = replace.split("_");
            Long start = Long.valueOf(split[0]);
            Long end = Long.valueOf(split[1]);
            if (time < end && time > start){
                List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(ScekillConstants.SKU_CACHE_PREFIX);
                List<String> multiGet = hashOps.multiGet(range);
                if (multiGet != null){
                    List<SeckillSkuRedisDto> dtoList = multiGet.stream().map(item -> {
                        SeckillSkuRedisDto dto = JSON.parseObject(item, SeckillSkuRedisDto.class);
                        return dto;
                    }).collect(Collectors.toList());
                    return dtoList;
                }
            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisDto getSecckillSessionBySkuId(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(ScekillConstants.SKU_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (ObjectUtil.isNotNull(keys)){
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                boolean matches = Pattern.matches(regx, key);
                if (Boolean.TRUE.equals(matches)){
                    String json = hashOps.get(key);
                    SeckillSkuRedisDto dto = JSON.parseObject(json, SeckillSkuRedisDto.class);
                    return dto;
                }
            }
        }
        return null;
    }
}
